package com.pingan.stat.money24.service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;

import com.pingan.common.core.property.Properties;
import com.pingan.common.util.ShellExecutor;

@Component
public class Money24StatService {

	@Properties(name = "money24.output.path")
	private String money24OutputPath;

	@Properties(name = "money24.pv.uv")
	private String money24PVUVShell;

	@Properties(name = "money24.new.cookie.user")
	private String money24NewCookeUserShell;

	@Properties(name = "money24.old.cookie.user")
	private String money24OldCookeUserShell;

	@Properties(name = "money24.url.stat")
	private String money24UrlStatShell;

	@Properties(name = "money24.url.stat.hql.file")
	private String money24UrlStatCreateHQLShell;

	@Properties(name = "scp.shell")
	private String scpShell;

	@Resource
	private ShellExecutor shellExecutor;

	@Resource
	private Money24UrlStatService money24UrlStatService;

	public void stat(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String yyyyMMdd = sdf.format(date);
		String output = money24OutputPath + "/" + yyyyMMdd;
		String timestamp = getTimestamp(date);

		System.out.println("----- clean up output path");
		cleanUpPath(output);

		System.out.println("------" + yyyyMMdd);
		System.out.println("----- stat pv uv");
		String[] pvUVParam = new String[] { yyyyMMdd, output };
		shellExecutor.excecute(money24PVUVShell, pvUVParam);

		System.out.println("----- stat new cookie user");
		String[] cookieUser = new String[] { yyyyMMdd, output, timestamp };
		shellExecutor.excecute(money24NewCookeUserShell, cookieUser);

		System.out.println("----- stat old cookie user");
		shellExecutor.excecute(money24OldCookeUserShell, cookieUser);

		System.out.println("----- stat url ");
		money24UrlStatService.stat(output, money24UrlStatCreateHQLShell,
				money24UrlStatShell, yyyyMMdd, date);

		System.out.println("----- scp output ");
		String[] scpParams = new String[] { output };
		shellExecutor.excecute(scpShell, scpParams);
	}

	public void cleanUpPath(String output) {
		File file = new File(output);
		if (file.isDirectory()) {
			try {
				FileUtils.forceDelete(file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		file.mkdirs();
	}

	public String getTimestamp(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		String t = Long.valueOf(cal.getTimeInMillis()).toString();

		return t;
	}
}
